package com.codi.bus.core.service.organ.impl;

import com.codi.base.domain.BaseServiceImpl;
import com.codi.base.exception.BaseAppException;
import com.codi.base.util.Assert;
import com.codi.bus.core.dao.OrgFileBucketDao;
import com.codi.bus.core.dao.OrgFileDao;
import com.codi.bus.core.domain.OrgFile;
import com.codi.bus.core.domain.OrgFileBucket;
import com.codi.bus.core.resultModel.OrganFileResult;
import com.codi.bus.core.service.organ.OrgFileService;
import com.codi.superman.base.manager.FileUploadMgr;
import com.codi.superman.base.service.SysDBService;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by wangzhenhao on 2017/9/11.
 */
@Service
@Transactional(readOnly = true)
public class OrgFileServiceImpl extends BaseServiceImpl implements OrgFileService{

    @Resource
    private OrgFileDao orgFileDao;

    @Resource
    private OrgFileBucketDao orgFileBucketDao;

    @Resource(name = "sysDBService")
    private SysDBService sysDBService;

    @Autowired
    private FileUploadMgr fileUploadMgr;

    @Override
    public OrgFile query(Long fileId) {
        return orgFileDao.selectByPrimaryKey(fileId);
    }

    @Override
    @Transactional(readOnly = false)
    public OrgFile save(OrganFileResult organFileResult) throws BaseAppException {
        Assert.notNull(organFileResult);

        OrgFile orgFile = new OrgFile();
        organFileResult.setState(0);
        Date now = new Date();
        BeanUtils.copyProperties(organFileResult, orgFile);

        orgFile.setCreateDate(now).setUpdateDate(now).setState(OrgFileDao.STATE_A);

        Long userId = organFileResult.getUserId();
        String fileType = organFileResult.getFileType();
        Long profileId = organFileResult.getProfileId();
        OrgFile checkExist = orgFileDao.selectByUserIdAndFileType(userId, fileType,profileId);

        logger.info("******************");
        logger.info("{}", checkExist);

        if (checkExist == null) {
            logger.debug("------fileInfo={}", orgFile);
            orgFileDao.insertSelective(orgFile);
        } else {
            orgFile.setId(checkExist.getId());
            orgFileDao.updateByPrimaryKeySelective(orgFile);
        }

        return orgFile;
    }

    @Override
    public OrgFile getOrgFileByUserIdAndFileType(Long userId, String fileType,Long profileId) {
        OrgFile checkExist = orgFileDao.selectByUserIdAndFileType(userId, fileType,profileId);

        return checkExist;
    }

    @Override
    public OrgFile getOrgFileByUserIdAndFileTypeAndProfileId(Long userId, String fileType, Long profileId) {
        OrgFile checkExist = orgFileDao.selectByUserIdAndFileTypeAndProfileId(userId, fileType, profileId);

        return checkExist;
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(Long id) throws BaseAppException {
        OrgFile orgFile = orgFileDao.selectByPrimaryKey(id);
        Assert.notNull(orgFile);

        // 先删除资源
        logger.debug("going to delete file={}", orgFile);

        OrgFileBucket bucket = orgFileBucketDao.selectByPrimaryKey(orgFile.getBucketId());
        logger.debug("file in bucket[{}]", bucket.getBucketCode());
        fileUploadMgr.deleteFile(bucket.getBucketCode(), orgFile.getFileName());

        orgFileDao.deleteByPrimaryKey(orgFile.getId());

        logger.debug("file deleted.");
        return 0;
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(String uniqueFileName) throws BaseAppException {
        Assert.notNull(uniqueFileName);

        return orgFileDao.deleteByUniqueFileName(uniqueFileName);
    }

    @Override
    @Transactional(readOnly = false)
    public int update(OrgFile orgFile) throws BaseAppException {
        Assert.notNull(orgFile);
        Assert.notNull(orgFile.getId());

        logger.debug("fileId={},desc={}", orgFile.getId(), orgFile.getDescription());

        //待更新字段
        OrgFile record = new OrgFile();
        record.setId(orgFile.getId());
        record.setDescription(orgFile.getDescription());
        record.setUpdateDate(new Date());

        return orgFileDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<OrganFileResult> queryFiles(Integer pageIndex, Integer pageSize) throws BaseAppException {
        return orgFileDao.queryFiles(pageIndex, pageSize);
    }

    @Override
    public List<OrganFileResult> queryFilesBySearchContent(Integer pageIndex, Integer pageSize, String searchContent) {

        return null;
    }

    @Override
    public Long queryFilesCount() throws BaseAppException {
        return sysDBService.getCount("ORG_FILE", "ID");
    }

    @Override
    public List<OrganFileResult> queryFilesByFileName(String fileName, Integer pageIndex, Integer pageSize) {
        String mimeType = "image";

        return orgFileDao.queryFilesByFileName(fileName, pageIndex, pageSize, mimeType);
    }

    @Override
    public List<OrganFileResult> queryFilesByUserId(Long userId) {

        return orgFileDao.queryFilesByUserId(userId);
    }

    @Override
    public List<OrganFileResult> queryFilesByUserIdAndProfileId(Long userId, Long profileId) {
        return orgFileDao.queryFilesByUserIdAndProfileId(userId, profileId);
    }

    @Override
    public List<OrganFileResult> queryFilesByProfileId(Long profileId) {
        return orgFileDao.queryFilesByProfileId(profileId);
    }

    @Override
    public int queryCountByFileName(String fileName) {
        String mimeType = "image";

        return orgFileDao.queryCountByFileName(fileName, mimeType);
    }

    @Override
    public boolean checkDataIntegrity(Long userId, Long profileId) {
//        int fileCount = orgFileDao.queryCountByUserId(userId);
//
//        if (fileCount < 6) {
//            return false;
//        }
        List<OrganFileResult> organFileResults = orgFileDao.queryFilesByProfileId(profileId);

        if (organFileResults != null) {
            int size = 0;

            for (OrganFileResult organFileResult : organFileResults) {
                String fileType = organFileResult.getFileType();

                if (! Strings.isNullOrEmpty(fileType)) {
                    switch (fileType) {
                        case "businessLicense" :
                            size++; break;
                        case "identifyCard_positive" :
                            size++; break;
                        case "identifyCard_back" :
                            size++; break;
                        case "bankAccountCertificate" :
                            size++; break;
                        case "authorization" :
                            size++; break;
                        case "preparatorySealCard" :
                            size++; break;
                    }
                }
            }

            if (size != 6) {
                return false;
            }
        } else {
            return false;
        }

//        if (isThreeInOne) {
//            if (fileCount < 8) {
//                return false;
//            }
//        } else {
//            if (fileCount != 9) {
//                return false;
//            }
//        }

        return true;
    }

    @Override
    public List<OrganFileResult> queryPictures(Integer pageIndex, Integer pageSize) {
        String mimeType = "image";

        return orgFileDao.queryPictures(pageIndex, pageSize, mimeType);
    }

    @Override
    public int queryPictureCount() {
        String mimeType = "image";

        return orgFileDao.queryPictureCount(mimeType);
    }
}
